﻿using Api1.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Api1.Service
{

    class InterfaceService : BaseService<Interfaces>
    {
        private static InterfaceService instance;
        private InterfaceService() {

        }
        public static InterfaceService GetInstance() {
            if (instance == null)
            {
                instance = new InterfaceService();
            }
            return instance;
        }
        /// <summary>
        /// 获取原卡号
        /// </summary>
        /// <returns></returns>
        public String GetOriginalCardNo(String card_no) {
           String original_card= ScalarForString(String.Format("select card_no from m_interface where is_original=1 and  id= (select original_id from m_interface where is_original=0 and card_no='{0}')", card_no));
            if (original_card == null || original_card.Length < 8) {
                return card_no;
            }
            return original_card;

        }
        /// <summary>
        /// 根据卡号查找对象
        /// </summary>
        /// <param name="card_no"></param>
        /// <returns></returns>        
        public Interfaces FindByCardno(String card_no) {
            if (String.IsNullOrWhiteSpace(card_no)) {
                throw new ArgumentException("参数card_no 为空");
            }
            return Find(String.Format("select * from m_interface where card_no='{0}'", card_no));
        }
        /// <summary>
        /// 卡号是否前台验证
        /// 0 没有验卡 1已经验卡通过
        /// </summary>
        /// <returns></returns>
        public int IsVarify(String card_no) {
            return Count(String.Format("select count(1) as count from m_varify_record where card_no='{0}' and is_in=0 and now()<date_add(create_time,INTERVAL 1 HOUR) ", card_no));
        }
        /// <summary>
        /// 免扣时间访问内
        /// </summary>
        /// <param name="Card_No"></param>
        /// <returns></returns>
        public Boolean Is_In_Free_Time(String Card_No) {
            //免扣次时间(分钟)
            int pvalue = InterfaceService.ScalarForInt("select pvalue  from m_system_set where id =1");
            //上次扣次时间
            String sub_time = InterfaceService.ScalarForString(String.Format("select  sub_time  from m_behavior_log where card_no='{0}' and sub_time is not null and LENGTH(sub_time)>4 and behavior_status=1 and behavior_type=1 order by id desc limit 1", Card_No));
            if (String.IsNullOrWhiteSpace(sub_time)) {
                return false;
            }
            if (DateTime.Now.AddMinutes(0 - pvalue).ToString("yyyy-MM-dd HH:mm:ss").CompareTo(sub_time) > 0)
            {
                return false;
            }
            else {
                return true;
            }
            
        }
        /// <summary>
        /// 临时卡自减1
        /// </summary>
        public void SetDes(Interfaces obj) {
           ExcuteSql(String.Format("update m_interface set surplus_num=surplus_num-1  where id={0}", obj.Id));
        }
        /// <summary>
        /// 获取验证记录 Id
        /// 如果结果不存在则返回0
        /// </summary>
        public Int32 GetVarifyRecord(String Card_No) {
            int time = ScalarForInt("select pvalue from m_system_set where id=3");
            List<Dictionary<String, Object>> obj= SelectDictionaryList(String.Format("select is_in,create_time from m_varify_record where card_no='{0}'  order by id desc", Card_No));
            if (obj.Count==0) {
                return 0;
            }
            else {
                if (obj[0]["is_in"].ToString().Equals("0")) {
                    return 1;
                }
                String c_t = obj[0]["create_time"].ToString();
                String now1 = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                String now=DateTime.Now.AddMinutes(0-time).ToString("yyyy-MM-dd HH:mm:ss");
                if (now.CompareTo(c_t) > 0)
                {
                    return 0;
                }
                else {
                    return 1;

                }               
            }
        }
        /// <summary>
        /// 数据库是否有人脸特征值
        /// </summary>
        /// <param name="Card_No"></param>
        /// <returns></returns>
        public Dictionary<String, Object> GetFaceCode(String Card_No)
        {
             List<Dictionary<String,Object>> obj = SelectDictionaryList(String.Format("select  card_no, face1,face2,face3  from m_face_code where card_no='{0}' limit 1", Card_No));
            if (obj.Count == 0)
            {
                return null;
            }
            else {

                if (obj[0]["face1"] == null || obj[0]["face1"].ToString().Length < 500) {
                    return null;
                }
            }
            return obj[0];
        }
        /// <summary>
        /// 修改前台验证表---进入闸机
        /// </summary>
        public void UpdateVarifyRecord(String Card_No) {
            String sql=String.Format("update m_varify_record set is_in=1 , in_time='{0}' where card_no='{1}' order by id desc limit 1 ", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Card_No);
            ExcuteSql(sql);
        }
        /// <summary>
        /// 获取权限值
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool HasAuthCode(String ids,String brackmation_no) {
            if (String.IsNullOrWhiteSpace(ids)) {
                return false;
            }
            List<String> list=InterfaceService.SelectColumn(String.Format("select code from  m_sliding_door where id in({0})", ids));
            if (list.Contains(brackmation_no))
            {
                return true;
            }
            else {
                return false;
            }
        }
        /// <summary>
        /// 从模板库中获取特征码
        /// </summary>
        /// <param name="card_no">卡号</param> 
        /// <returns>多个模板  ， 隔开</returns>
        public String GetModelData(String card_no,String varify_type) {
            StringBuilder stringBuider = new StringBuilder();
            String datas = InterfaceService.ScalarForString(String.Format("select datas from m_model_data where card_no='{0}' and varify_type='{1}' ", card_no, varify_type));
            if (String.IsNullOrWhiteSpace(datas))
            {
                return "";
            }
            else
            {
                JObject obj = JObject.Parse(datas);
                JToken record = obj;
                foreach (JProperty jp in record) {
                    stringBuider.Append(jp.Value).Append(",");
                }
            }
            return stringBuider.ToString();
        }
        /// <summary>
        /// 上传特征码
        /// </summary>
        /// <param name="card_no">卡号</param>
        /// <param name="newDatas">数据</param>
        /// <param name="score">分数</param>
        /// <param name="varify_type">验证类型</param>
        public  void UploadModelData (String card_no, String newDatas,String score, String varify_type)
        {
            //原来卡号
            card_no = InterfaceService.GetInstance().GetOriginalCardNo(card_no);
            String  _score = ((Int32)Convert.ToDouble(score)).ToString();
            String datas = InterfaceService.ScalarForString(String.Format("select datas from m_model_data where card_no='{0}' and varify_type='{1}' ",card_no,varify_type));
            if (String.IsNullOrWhiteSpace(datas))
            {   
                //新增模板
                InterfaceService.ExcuteSql(String.Format("insert into m_model_data (card_no,datas,varify_type) value('{0}','{1}','{2}')", card_no, new JObject(new JProperty(_score, newDatas)).ToString(), varify_type));
            }
            else {
                // 修改模板
                JObject obj = JObject.Parse(datas);

                if (obj.Count < 5)
                {
                    obj[_score] = newDatas;
                   
                }
                else {
                    foreach (var item in obj)
                    {
                        if (item.Key.CompareTo(_score) < 0) {
                            obj.Remove(item.Key);
                            obj[_score] = newDatas;
                            break;
                        }
                    }
                }
                String sql = String.Format("update m_model_data set datas='{0}' where  card_no='{1}' and varify_type='{2}' ", obj.ToString(), card_no, varify_type);
                InterfaceService.ExcuteSql(sql);
            }
        }
        /// <summary>
        /// 获取AK第一版会员数据
        /// </summary>
        /// <returns></returns>
        public static List<TestMember> GetTestMember()
        {
            int count= Count("SELECT count(1) from information_schema.`TABLES` WHERE TABLE_NAME='test_interface' and TABLE_SCHEMA='akv2'");
            if (count < 1) {
                MessageBox.Show("test_interface  不存在");
                return null;
            }

            int count1 = Count("SELECT count(1) from m_interface");

            if (count1 > 0)
            {
                MessageBox.Show("m_interface  存在数据");
                return null;
            }
            using (var db = GetDbFactory().Open())
            {
                
                return db.Select<TestMember>("select * from test_interface ");
            }
        }
        
    }
    /// <summary>
    /// 
    /// </summary>
    public class TestMember{
        
        public String Card_No { get; set; }
        public  int Owner_Type { get; set; }
        public String Fingerprint { get; set; }
        public String Create_Time { get; set; }
        public String Name { get; set; }
        public String Mobile { get; set; }
             
    }

}
